package com.pig4cloud.pig.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.admin.api.entity.MetaEntityEntity;
import com.pig4cloud.pig.admin.api.entity.MetaFieldEntity;
import com.pig4cloud.pig.admin.api.entity.SysMenu;
import com.pig4cloud.pig.admin.entity.vo.FlowFieldVO;
import com.pig4cloud.pig.admin.mapper.MetaEntityMapper;
import com.pig4cloud.pig.admin.service.CommonService;
import com.pig4cloud.pig.admin.service.MetaEntityService;
import com.pig4cloud.pig.admin.service.MetaFieldService;
import com.pig4cloud.pig.admin.service.SysMenuService;
import com.pig4cloud.pig.admin.util.MetaFieldUtils;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.enums.FieldType;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.mybatis.base.Group;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 实体表
 *
 * @author pig
 * @date 2024-09-23 15:56:01
 */
@Service
@AllArgsConstructor
public class MetaEntityServiceImpl extends ServiceImpl<MetaEntityMapper, MetaEntityEntity> implements MetaEntityService {
	private final MetaFieldService metaFieldService;
	private final CommonService commonService;
	private final SysMenuService sysMenuService;

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R<Boolean> saveMetaEntityEntity(MetaEntityEntity metaEntity) {
		MetaEntityEntity entity = getOne(Wrappers.lambdaQuery(MetaEntityEntity.class).eq(MetaEntityEntity::getLabel, metaEntity.getLabel()));
		if (Objects.nonNull(entity)) {
			return R.failed("实体名称:" + entity.getLabel() + " 已存在");
		}
		// 随机生成5位随机字母表名
		int count = 0;
		while (true) {
			String physicalName = "common_" + metaEntity.getLabel() + "_" + RandomUtil.randomString(count++).toLowerCase();
			if (ObjectUtil.isNull(baseMapper.getMetaEntityEntity(physicalName))) {
				metaEntity.setPhysicalName(physicalName);
				break;
			}
		}
		metaEntity.setFlowStatus(CommonConstants.STATUS_NORMAL);
		if (save(metaEntity)) {
			List<MetaFieldEntity> defualtFieldList = MetaFieldUtils.getDefualtFieldList(metaEntity.getId());
			metaFieldService.saveBatch(defualtFieldList);
		}
		commonService.createBaseEntity(metaEntity.getPhysicalName());
		saveMenu(metaEntity);
		return R.ok(true);
	}

	private void saveMenu(MetaEntityEntity metaEntity) {
		SysMenu sysMenu = new SysMenu();
		sysMenu.setIcon("ele-Coin");
		sysMenu.setName(metaEntity.getName() + "管理");
		sysMenu.setEnName(metaEntity.getLabel());
		sysMenu.setPermission("");
		sysMenu.setMenuType("0");
		sysMenu.setSortOrder(8);
		sysMenu.setParentId(1843933570130972674L);
		sysMenu.setVisible("1");
		sysMenu.setKeepAlive("0");
		sysMenu.setEmbedded("0");
		sysMenu.setPath("/common/index?label=" + metaEntity.getLabel());
		sysMenuService.save(sysMenu);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public R<Boolean> removeMetaEntity(Long[] ids) {
		removeBatchByIds(CollUtil.toList(ids));
		if (ObjectUtil.isNotEmpty(ids)) {
			metaFieldService.remove(Wrappers.lambdaQuery(MetaFieldEntity.class).in(MetaFieldEntity::getEntityId, ids));
		}
		return R.ok(true);
	}

	@Override
	public R<Boolean> saveShowField(String id, List<String> metaFieldEntityList) {
		MetaEntityEntity metaEntity = getById(id);
		if (ObjectUtil.isNull(metaEntity)) {
			return R.failed("实体不存在");
		}
		metaEntity.getFormJson().setBaseShowFieldList(metaFieldEntityList);
		return R.ok(updateById(metaEntity));
	}

	@Override
	public R<Boolean> saveCondition(String id, Group groupConditions) {
		MetaEntityEntity metaEntity = getById(id);
		if (ObjectUtil.isNull(metaEntity)) {
			return R.failed("实体不存在");
		}
		metaEntity.getFormJson().setGroupsConditions(CollUtil.toList(groupConditions));
		return R.ok(updateById(metaEntity));
	}

	@Override
	public R<Boolean> saveFormJson(String id, List<Map<String, Object>> formJson) {
		MetaEntityEntity metaEntity = getById(id);
		if (ObjectUtil.isNull(metaEntity)) {
			return R.failed("实体不存在");
		}
		metaEntity.getFormJson().setFormJson(formJson);
		return R.ok(updateById(metaEntity));
	}

	@Override
	public R<List<FlowFieldVO>> getFlowFieldById(String id) {
		List<MetaFieldEntity> metaFieldEntityList = metaFieldService.list(Wrappers.lambdaQuery(MetaFieldEntity.class).eq(MetaFieldEntity::getEntityId, id));
		List<FlowFieldVO> flowFieldVOList = metaFieldEntityList.stream().filter(field -> ObjectUtil.equal(CommonConstants.NO, field.getSystemFieldFlag())).map(field -> {
			FlowFieldVO flowFieldVO = new FlowFieldVO();
			flowFieldVO.setId(field.getLabel());
			flowFieldVO.setLabel(field.getName());
			flowFieldVO.setName(FieldType.getByValue(field.getType()).getElType());
			return flowFieldVO;
		}).toList();
		return R.ok(flowFieldVOList);
	}


}
